package com.hkts.beltweigher.websocket;


import com.alibaba.fastjson.JSON;
import com.hkts.beltweigher.websocket.sendUtil.NettySendUtil;
import com.hkts.beltweigher.websocket.sendUtil.ResultMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

import static com.hkts.beltweigher.synchronizationtask.HomePageCache.homeCache;

/**
 * MyWebSocketHandler
 * WebSocket处理器，处理websocket连接相关
 *
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //添加到channelGroup通道组

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        log.info("与客户端用户ip地址：[{}]断开连接，通道关闭！", ctx.channel().remoteAddress().toString());
        if (MyChannelHandlerPool.channelGroup.find(ctx.channel().id()) != null) {
            MyChannelHandlerPool.channelGroup.remove(ctx.channel());
            log.info("与pc端用户ip地址：[{}]断开连接，通道关闭！", ctx.channel().remoteAddress().toString());
        } else if (MyChannelHandlerPool.wechatChannelGroup.find(ctx.channel().id()) != null) {
            MyChannelHandlerPool.wechatChannelGroup.remove(ctx.channel());
            log.info("与小程序端用户ip地址：[{}]断开连接，通道关闭！", MyChannelHandlerPool.wechatChannelGroup.toString());
        }
        //关闭通道
        ctx.channel().close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            log.info("接收到的uri是：{}", uri);
            Map paramMap = NettySendUtil.getUrlParams(uri);

            log.info("接收到的参数是：{}", JSON.toJSONString(paramMap));
            //如果url包含参数，需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                log.info("url：{}", newUri);
                request.setUri(newUri);
            }
            /*
             * 将参数及Channel id 缓存到redis
             * */
            if (paramMap.size() > 0 && paramMap.get("paramterType").toString().equals("pc")) {
                MyChannelHandlerPool.channelGroup.add(ctx.channel());
                log.info("与pc端客户端建立连接，通道开启！");
            }
        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            String test = frame.text();

            if (MessageConstants.PING_MSG.equals(test)) {
                NettySendUtil.sendPongMsg(ctx);
                //return;
            }
            //log.info("获取客户端数据：{}", test);

        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws
            Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ExceptionPrintUtils.exceptionPrintUtils(cause);
        super.exceptionCaught(ctx, cause);
    }


}